<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 管理人员 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button icon="el-icon-circle-plus" class="handle-del mr10 mybutton2" @click="addBook">新增管理员</el-button>
                <el-input v-model="query.name" placeholder="管理员人名" class="handle-input mr10"></el-input>
                <el-button class="mybutton1" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                stripe
            >
                <el-table-column prop="manager_id" label="编号" width="55" align="center"></el-table-column>
                <el-table-column prop="manager_name" width="100" label="管理员"></el-table-column>
                <el-table-column label="账号" width="100" prop="manager_accout"> </el-table-column>
                <el-table-column label="性别" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.manager_sex === '男' ? 'primary' : scope.row.manager_sex === '女' ? 'danger' : ''">{{
                            scope.row.manager_sex
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="身份证号" width="200" align="center" prop="manager_idCard"> </el-table-column>

                <el-table-column label="负责工作" width="100" align="center" prop="manager_job"> </el-table-column>

                <el-table-column label="电话号码" width="120" align="center" prop="manager_phone"> </el-table-column>
                <el-table-column label="邮箱" width="170" align="center" prop="manager_email"> </el-table-column>
                <el-table-column label="家庭地址" width="200" prop="manager_address"> </el-table-column>
                <el-table-column label="权限" width="100" align="center" prop="manager_role"> </el-table-column>

                <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <el-button type="warning" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)" class="mybutton2"
                            >重置密码</el-button
                        >
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)" class="mybutton3"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="新增管理员" :visible.sync="addVisible" width="50%">
            <el-form ref="addForm" :model="addForm" :rules="addFormRule" label-width="100px">
                <el-form-item label="管理员名" prop="manager_name">
                    <el-input v-model="addForm.manager_name"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="manager_sex">
                    <el-select v-model="addForm.manager_sex" placeholder="性别">
                        <el-option key="1" label="男" value="男"></el-option>
                        <el-option key="2" label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证号" prop="manager_idCard">
                    <el-input v-model="addForm.manager_idCard"></el-input>
                </el-form-item>
                <el-form-item label="负责工作" prop="manager_job">
                    <el-input v-model="addForm.manager_job"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="manager_phone">
                    <el-input v-model="addForm.manager_phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="manager_email">
                    <el-input v-model="addForm.manager_email"></el-input>
                </el-form-item>
                <el-form-item label="家庭地址" prop="manager_address">
                    <el-input v-model="addForm.manager_address"></el-input>
                </el-form-item>
                <el-form-item label="权限" prop="manager_role">
                    <el-select v-model="addForm.manager_role" placeholder="权限">
                        <el-option key="1" label="admin" value="admin"></el-option>
                        <el-option key="2" label="editor" value="editor"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button class="mybutton2" @click="addVisible = false">取 消</el-button>
                <el-button class="mybutton1" @click="addSure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'basetable',
    data() {
        // 验证手机号的规则
        const checkMobile = (rule, value, cb) => {
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
            if (regMobile.test(value)) {
                // 合法的手机号码
                return cb();
            }
            cb(new Error('手机号码格式不正确'));
        };
        const chinaIdentityValid = (rule, value, callback) => {
            if (!value) {
                return callback();
            }
            const city = {
                11: '北京',
                12: '天津',
                13: '河北',
                14: '山西',
                15: '内蒙古',
                21: '辽宁',
                22: '吉林',
                23: '黑龙江 ',
                31: '上海',
                32: '江苏',
                33: '浙江',
                34: '安徽',
                35: '福建',
                36: '江西',
                37: '山东',
                41: '河南',
                42: '湖北 ',
                43: '湖南',
                44: '广东',
                45: '广西',
                46: '海南',
                50: '重庆',
                51: '四川',
                52: '贵州',
                53: '云南',
                54: '西藏 ',
                61: '陕西',
                62: '甘肃',
                63: '青海',
                64: '宁夏',
                65: '新疆',
                71: '台湾',
                81: '香港',
                82: '澳门',
                91: '国外'
            };
            if (!value || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(value)) {
                callback(new Error('身份证号格式错误'));
            } else if (!city[value.substr(0, 2)]) {
                callback(new Error('身份证号格式错误'));
            } else {
                // 18位身份证需要验证最后一位校验位
                if (value.length === 18) {
                    const code = value.split('');
                    // ∑(ai×Wi)(mod 11)
                    // 加权因子
                    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                    // 校验位
                    const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                    let sum = 0;
                    let ai = 0;
                    let wi = 0;
                    for (let i = 0; i < 17; i++) {
                        ai = code[i];
                        wi = factor[i];
                        sum += ai * wi;
                    }
                    if (parity[sum % 11].toString() !== code[17]) {
                        callback(new Error());
                    }
                }
            }
            callback();
        };
        return {
            page: 1,
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addVisible: false,
            addForm: {},
            addFormRule: {
                manager_idCard: [
                    { required: true, message: '请输入管理员身份证号', trigger: 'blur' },
                    {
                        pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
                        message: '请输入正确的证件号',
                        trigger: 'blur'
                    },
                    { validator: chinaIdentityValid, trigger: 'blur' }
                ],
                manager_address: [{ required: true, message: '请输入管理员家庭住址', trigger: 'blur' }],
                manager_phone: [
                    { required: true, message: '请输入管理员电话号码', trigger: 'blur' },
                    {
                        validator: checkMobile,
                        trigger: 'blur'
                    }
                ],
                manager_sex: [{ required: true, message: '请选择管理员性别', trigger: 'blur' }],
                manager_job: [{ required: true, message: '请输入管理员工作', trigger: 'blur' }],
                manager_role: [{ required: true, message: '请选择管理员权限', trigger: 'blur' }],
                manager_email: [{ required: true, message: '请输入管理员邮箱', trigger: 'blur' }],
                manager_name: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }]
            },
            fileList: []
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            axios({
                method: 'get',
                url: 'http://172.22.10.90:3000/managers',
                params: {
                    page: this.page
                }
            }).then((res) => {
                this.tableData = res.data.data;
            });

            axios({
                method: 'get',
                url: 'http://172.22.10.90:3000/managers/pagetotal'
            }).then((res) => {
                this.pageTotal = res.data.data.length;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(role) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios({
                        method: 'delete',
                        url: 'http://172.22.10.90:3000/managers/delete',
                        params: {
                            manager_id: role.manager_id
                        }
                    }).then((res) => {
                        this.getData();
                    });
                    this.$message.success('删除成功');
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        addBook() {
            this.addVisible = true;
        },
        addSure() {
            axios({
                method: 'post',
                url: 'http://172.22.10.90:3000/managers/add',
                params: this.addForm
            }).then((res) => {
                this.getData();
                this.addVisible = false;
                this.$message.success('增加管理员成功!');
            });
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(role) {
            this.$confirm('确定要重置吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios({
                        method: 'put',
                        url: 'http://172.22.10.90:3000/managers/repassword',
                        params: {
                            manager_id: role.manager_id
                        }
                    }).then((res) => {});
                    this.$message.success('重置成功');
                })
                .catch(() => {});
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.page = val;
            this.getData();
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mybutton1 {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(108, 174, 194);
}
.mybutton1:hover {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(3, 58, 161);
}

.mybutton2 {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(250, 136, 55);
}
.mybutton2:hover {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(219, 107, 28);
}

.mybutton3 {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(197, 45, 7);
}
.mybutton3:hover {
    border: 0;
    color: #fff;
    border-radius: 15px;
    background-color: rgb(150, 33, 3);
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
